#include "sort.h"

static int *aux;

static void sort(int arr[], int lo, int mid, int hi) {
    int i = lo, j = mid+1;
    for (int k = lo; k <= hi; k++) {
        aux[k] = arr[k];
    }

    for (int k = lo; k <= hi; k++) {
        if (i > mid) arr[k] = aux[j++];
        else if (j > hi) arr[k] = aux[i++];
        else if (aux[i] > aux[j]) arr[k] = aux[j++];
        else arr[k] = aux[i++];
    }

}

static void post_merge(int arr[], int lo, int hi) {
    if (lo >= hi) return;
    int mid = (hi + lo) / 2;
    post_merge(arr, lo, mid);
    post_merge(arr, mid+1, hi);
    sort(arr, lo, mid, hi);
}

// 自顶向下的并归排序
void td_merge(int arr[], int size) {
    aux = malloc(size * sizeof(int));

    post_merge(arr, 0, size-1);

    free(aux);
}

// 自底向上的并归排序
void bu_merge(int arr[], int size) {
    aux = malloc(size * sizeof(int));

    for (int i = 1; i < size ; i *= 2) {
        for (int j = 0; j < size - i; j += 2*i) {
            sort(arr, j, j+i-1, min(j+2*i-1, size-1));
        }
    }

    free(aux);
}
